package com.aat.dxfy.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpPoolUtil {

	public static PoolingHttpClientConnectionManager pools;

	static {
		LayeredConnectionSocketFactory sslsf = null;
		try {
			sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("https", sslsf).register("http", new PlainConnectionSocketFactory()).build();
		pools = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		pools.setMaxTotal(200);
		pools.setDefaultMaxPerRoute(20);
	}

	public static CloseableHttpClient getHttpClient() {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pools).build();
		return httpClient;
	}

	public static byte[] getImg(String uri) {
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		HttpGet request = new HttpGet(uri);
		byte[] bs = null;
		try {
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				InputStream ins = entity.getContent();
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				byte[] bs1 = new byte[1024];
				int res = 0;
				while((res = ins.read(bs1)) > -1 ) {
					out.write(bs1, 0, res);
				}
				bs = out.toByteArray();
				out.flush();
				out.close();
				ins.close();
				return bs;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.releaseConnection();
			}

			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
	
	public static String get(String uri) {
		//CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpClient httpClient = getHttpClient();
		CloseableHttpResponse response = null;
		HttpGet request = new HttpGet(uri);
		try {
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(entity);
				return content;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.releaseConnection();
			}

			try {
				if (response != null) {
					response.close();
				}
				/*
				 if (httpClient != null) {
					httpClient.close();
				}
				 */
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}

	public static String post(String uri, Map<String, String> params) {
		CloseableHttpClient httpClient = getHttpClient();//HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost request = new HttpPost(uri);
		try {
			if (params != null && params.size() > 0) {
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				Set<Entry<String, String>> sets = params.entrySet();
				for (Entry<String, String> entry : sets) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				request.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			}

			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(entity);
				return content;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.releaseConnection();
			}

			try {
				if (response != null) {
					response.close();
				}
				/*
				 if (httpClient != null) {
					httpClient.close();
				}
				 */
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}

	public static HttpClientConnectionManager init() {
		try {
			SSLConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
			RegistryBuilder<ConnectionSocketFactory> rb1 = RegistryBuilder.create();
			rb1.register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf);
			Registry<ConnectionSocketFactory> registry = rb1.build();
			return new PoolingHttpClientConnectionManager(registry);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getSsl(String uri) {

		CloseableHttpClient httpClient = HttpClients.createMinimal(init());
		CloseableHttpResponse response = null;
		HttpGet request = new HttpGet(uri);
		try {
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(entity);
				return content;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.releaseConnection();
			}

			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}

	public static String postSsl(String uri, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createMinimal(init());
		CloseableHttpResponse response = null;
		HttpPost request = new HttpPost(uri);
		try {
			if (params != null && params.size() > 0) {
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				Set<Entry<String, String>> sets = params.entrySet();
				for (Entry<String, String> entry : sets) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				request.setEntity(new UrlEncodedFormEntity(nvps));
			}

			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(entity);
				return content;
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (request != null) {
				request.releaseConnection();
			}

			try {
				if (response != null) {
					response.close();
				}
				if (httpClient != null) {
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return null;
	}
}
